//
//  Connection.m
//  10.10网络请求作业2
//
//  Created by xwc on 14-10-10.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "Connection.h"

@interface Connection ()<UIAlertViewDelegate>

@end

@implementation Connection

+ (void)networkHandlerWith:(NSString *)str block:(void(^)(id result))block;
{
    //1.处理地址
    NSString *strURL = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strURL];
    
    //2.创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    request.HTTPMethod = @"get";
    
    //3.链接服务器
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        // 获取caches文件夹，用来保存缓存数据
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        // 文件名的选择有两种：1.接口的地址当做文件名 2.利用NSObject的哈希值
        
        NSInteger hash = [strURL hash];
//        NSLog(@"========%d", hash);
        NSString *filePath = [cachesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.plist", hash]];
        NSLog(@"--------%@", filePath);
        
        if (data != nil) {
            NSError *error = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            block(result);
            
            // 在这里写入本地（NSData/NSDictionary）
            
            // 利用归档类 将Data写入本地
            BOOL re = [NSKeyedArchiver archiveRootObject:data toFile:filePath];
            NSLog(@"%d", re);
            
        } else {
            NSLog(@"网络请求失败");
            
            // 在这里读取之前存储的数据
            
            // 反归档
            NSData *dataRead = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
            
            if (dataRead == nil) {
                
                UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"网络异常" message:@"请检查网络" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [view show];
                [view release];
                
            } else {
                
                id result = [NSJSONSerialization JSONObjectWithData:dataRead options:NSJSONReadingMutableContainers error:nil];
                block(result);
            
            }
     
        }
    }];
    
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
}



@end
